<template>
  <div class="cart-page">
    <h3>收货地址</h3>
    <hr />
    <el-row type="flex" justify="start">
      <el-col class="useraddress" :span="6" v-for="a in addrs" :key="a.id">
        <p>
          <input type="radio" :value="a.id" v-model="radio" />
          <span>{{a.province}} {{a.place}} {{a.area}} {{a.addr}}</span>
        </p>
        <p>手机：{{a.receiverPhone}}</p>
        <p>（{{a.receiver}}）收</p>
      </el-col>
    </el-row>
    <h2>全部商品</h2>
    <el-table
      :data="cartItems"
      row-key="id"
      border
      style="width: 100%"
      @selection-change="updateSelectedItems"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="商品信息" prop="productInfo" width="300">
        <template slot-scope="scope">
          <img :src="require(`@/${scope.row.img}`)" alt class="product-img" width="80" height="100" />
          <span>{{ scope.row.spuName }}</span>
          <span>{{ scope.row.color }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" prop="price" width="120">
        <template slot-scope="scope">￥{{ scope.row.buyPrice.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column label="数量" width="220">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.buyNum"
            :min="1"
            :max="99"
            @change="updateSelectedItems(selectedItems)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="金额" width="120">
        <template slot-scope="scope">￥{{ (scope.row.buyPrice * scope.row.buyNum).toFixed(2) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="removeItem(scope.row.id,scope.row.buyNum)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="cart-actions">
      <el-button type="text"></el-button>
      <div class="total-info">
        <!-- 添加挑战优惠券的按钮 -->
        <el-button @click="userCard">使用优惠券</el-button>
        <span>总价（不含运费）：￥{{ discountedTotal ? discountedTotal.toFixed(2) : totalPrice.toFixed(2) }}</span>
        <el-button type="primary" @click="addOrder" :disabled="isLoading">去结算</el-button>
      </div>
    </div>

    <!-- 我在这里添加了一个el-dialog标签 -->
    <el-dialog title="使用优惠券" :visible.sync="dialogVisible" width="60%">
      <el-row>
        <el-col
          v-for="(coupon, index) in couponData"
          :key="index"
          :xs="24"
          :sm="24"
          :md="12"
          :lg="8"
          :xl="6"
        >
          <el-card class="box-card" style="margin: 10px">
            <h3>{{ coupon.name }}</h3>
            <p>使用类型: {{ coupon.sortName }}</p>
            <p>要求金额: {{ coupon.usageAmount }}元</p>
            <p>抵用金额: {{ coupon.value }}元</p>
            <p>起始时间: {{ coupon.startAt }}</p>
            <p>截止时间: {{ coupon.endAt }}</p>

            <el-button type="primary" @click="useCoupon(coupon)">
              <!-- 根据优惠券是否被选中来更改按钮文本 -->
              {{ coupon === selectedCoupon ? '已使用' : '使用优惠券' }}
            </el-button>
          </el-card>
        </el-col>
      </el-row>

      <!-- 在对话框底部添加一个确认按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>

      <el-loading
        :fullscreen="true"
        lock
        :text="'加载中...'"
        :spinner="isLoading?'el-icon-loading':''"
        :background="'rgba(0, 0, 0, 0.7)'"
        :visible="isLoading"
      ></el-loading>
    </el-dialog>
  </div>
</template>
  
<script>
export default {
  data() {
    return {
      cartItems: [],
      selectAll: false,
      userId: "",
      phone: "",
      selectedItems: [],
      addrs: [],
      radio: "1",
      selectedAddressId: "",
      orderNum: "",
      dialogVisible: false,
      couponData: "",
      selectedCoupon: null, // 新加入选中的优惠券，初始为null
      selectedItemTotal: {}, // 新增一个用于保存各类商品的总计的对象,
      isLoading: false, // 在这里添加 isLoading
    };
  },
  computed: {
    totalPrice() {
      return this.selectedItems.reduce(
        (total, item) => total + item.buyPrice * item.buyNum,
        0
      );
    },
    discountedTotal() {
      const discountApplies =
        this.selectedCoupon &&
        this.selectedItemTotal[this.selectedCoupon.sortId] >=
          this.selectedCoupon.usageAmount;
      const discountAmount = discountApplies ? this.selectedCoupon.value : 0;

      return this.totalPrice - discountAmount;
    },
    selectedIds() {
      //将函数名修改为selectedIds
      return this.selectedItems.map(item => item.id); // 添加return关键字
    }
  },
  methods: {
    userCard() {
      //查用户优惠券
      this.$axios
        .get("api/zgyd-jifen/queryUsersCoupon/" + this.userId)
        .then(res => {
          if (res.data.code == 200) {
            this.couponData = res.data.data;
          }
        });
      this.dialogVisible = true;
    },

    useCoupon(coupon) {
      if (this.selectedCoupon === coupon) {
        this.selectedCoupon = null;
      } else {
        // 否则就选择这个优惠券
        this.selectedCoupon = coupon;
        this.updateSelectedItems(this.selectedItems.map(item => item));
      }
      const selectedTotal = this.selectedItemTotal[coupon.sortId] || 0;
      if (selectedTotal < coupon.usageAmount) {
        this.$message.warning("未达到优惠券使用条件");
        return;
      }
      coupon.used = true; // 将优惠券设置为已使用
      this.selectedCoupon = coupon; // 记录已使用的优惠券
      this.$message.success("优惠券已成功使用");
    },

    //删除商品
    removeItem(id, buyNum) {
      let param = new URLSearchParams();
      param.append("id", id);
      param.append("buyNum", buyNum);
      this.$axios.post("/api/zgyd-product/removeCart", param).then(res => {
        if (res.data.code === 200) {
          this.$message.success("删除成功！");
          this.getShoppingcart();
        }
      });
    },
    addOrder() {
      // 检查总价是否为0
      if (this.totalPrice === 0) {
        this.$message.warning("请选择商品");
        return; // 结束函数，不进行下一步
      }
      // 检查是否用了优惠卷
      if (this.selectedCoupon) {
        console.log("已经使用了优惠券");
        console.log(this.selectedCoupon);
        let couponId = this.selectedCoupon.id;
        this.$axios.get("/api/zgyd-jifen/updateUsersCoupon/" + couponId).then();
      }

      let skuOrderDto = {};
      skuOrderDto.items = this.selectedItems.map(item => ({
        id: item.id,
        quantity: item.buyNum,
        skuId: item.skuId
      }));
      skuOrderDto.totalPrice = this.discountedTotal
        ? this.discountedTotal
        : this.totalPrice;
      skuOrderDto.userId = this.userId;
      skuOrderDto.cartIds = this.selectedIds;
      skuOrderDto.phone = this.phone;
      skuOrderDto.addressId = this.selectedAddressId;
      let matchedAddress = this.addrs.find(a => a.id == this.selectedAddressId);
      if (matchedAddress) {
        skuOrderDto.province = matchedAddress.province; // 使用匹配的省份
      }
      // 检查是否用了优惠卷
      if (this.selectedCoupon) {
        console.log("已经使用了优惠券");
        skuOrderDto.couponId = this.selectedCoupon.userCouponId;
      } else {
        skuOrderDto.couponId = 0;
      }
      // 计算使用优惠券商品的数量
      if (this.selectedCoupon) {
        skuOrderDto.couponUsedItemCount = this.selectedItems
          .filter(item => item.sortId === this.selectedCoupon.sortId)
          .reduce((total, item) => total + item.buyNum, 0);
      } else {
        skuOrderDto.couponUsedItemCount = 0;
      }
      this.isLoading = true; // 开始加载请求
      // ...你的请求代码
      this.$axios
        .post("/api/rabbit/addSkuOrder", skuOrderDto)
        .then(res => {
          if (res.data.code == 500) {
          this.$message.warning(res.data.msg);
        }
        if (res.data.code === 200) {
          this.orderNum = res.data.data;
          console.log(this.orderNum);
          this.$message.success("结算成功！");
          this.$router.push({
            path: "/skuPay",
            query: {
              orderNum: this.orderNum,
              totalPrice: this.discountedTotal
                ? this.discountedTotal
                : this.totalPrice
            }
          });
        }
          this.isLoading = false; // 请求结束，取消加载状态
        })
        .catch(err => {
          console.error(err);
          this.isLoading = false; // 发生错误，取消加载状态
        });
    },

    getShoppingcart() {
      //查用户
      let param1 = new URLSearchParams();
      param1.append("phone", this.phone);
      this.$axios.post("/api/zgyd-user/queryUser", param1).then(res => {
        if (res.data.code === 200) {
          let userId = res.data.data.id;
          this.userId = userId;
          //查用户购物车
          let param = new URLSearchParams();
          param.append("userId", userId);
          this.$axios
            .post("/api/zgyd-product/getShoppingcart", param)
            .then(res => {
              if (res.data.code === 200) {
                this.cartItems = res.data.data;
              }
            });
        }
      });
    },
    updateSelectedItems(selected) {
      this.selectedItems = selected;
      this.selectedItemTotal = this.selectedItems.reduce((acc, item) => {
        if (acc[item.sortId]) {
          acc[item.sortId] += item.buyPrice * item.buyNum;
        } else {
          acc[item.sortId] = item.buyPrice * item.buyNum;
        }
        return acc;
      }, {});

      if (this.selectedCoupon) {
        const selectedTotal =
          this.selectedItemTotal[this.selectedCoupon.sortId] || 0;
        if (selectedTotal < this.selectedCoupon.usageAmount) {
          this.selectedCoupon = null; // 如果不满足条件，取消使用该优惠券
          this.$message.warning("由于您的选购商品变更，当前优惠券已取消使用");
        }
      }
    },
    //查用户地址
    queryAddrs() {
      let param = new URLSearchParams();
      param.append("phone", this.phone);
      this.$axios.post("/api/zgyd-user/queryAddress", param).then(res => {
        if (res.data.code === 200) {
          this.addrs = res.data.data;
        }
      });
    }
  },
  created() {
    this.phone = localStorage.getItem("username");
    this.getShoppingcart();
    this.queryAddrs();
    this.selectedAddressId = this.radio;
  },
  watch: {
    radio(newVal) {
      this.selectedAddressId = newVal;
    }
  }
};
</script>
  
<style scoped>
.cart-page {
  padding: 20px;
  max-width: 1000px;
  margin: auto;
}

h2 {
  margin-bottom: 20px;
}

.product-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}

.el-table .el-table__body-wrapper {
  overflow: visible;
}

.cart-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  align-items: center;
}

.total-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.el-button--primary {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: #fff;
}

.el-button--primary:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.product-img {
  width: 100px;
  height: 100px;
}

.useraddress {
  width: 280px;
  height: 130px;
  border: 1px solid #555;
  margin: 20px 10px;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.15);
  background-color: #fff;
  transition: all 0.3s ease-in-out;
  position: relative;
}

.useraddress p {
  margin: 0;
  padding: 0;
  line-height: 1.5;
}

.useraddress:hover {
  box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-10px);
}
</style>
  